class Dictionary < ActiveRecord::Base
  validates_presence_of :word
  validates_uniqueness_of :word, :scope => :flag
  validates_numericality_of :rank
  
  attr_accessor :import_file
  
  class << self
  
    def flag_options
      FLAGS.inject([]){ |arr, obj| arr << obj.reverse }
    end
    
    # import file encode must be utf8
    def import(file, flag = 0)
      return false if file.blank? or File.extname(file.original_filename) != ".txt"
      
      require 'iconv'
      file.readlines.each do |line|
        #word = Iconv.conv("utf8//IGNORE","GBK//IGNORE", line.strip)
        word = line.strip
        next if word =~ /^#/

        puts "Word: #{word}"
        find_or_create_by_word_and_flag(word, flag.to_i)
      end
      true
    end
  end
  
  def to_s
    word
  end
  
  def to_param
    "#{id}-#{word}"
  end
end
